package com.example.myapplication.DataBase;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication.R;

public class PreferencesActivity extends AppCompatActivity {
  TextView infoView;



  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.database_perferences_layout);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("SharedPreferences界面");
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    infoView = (TextView) findViewById(R.id.infoView);
    infoView.setVisibility(View.INVISIBLE);
    BindButton();
  }


  private void BindButton() {
    Button saveButton = (Button) findViewById(R.id.save_button);
    Button showInfoButton = (Button) findViewById(R.id.show_button);
    saveButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        SaveDataByPreference();
      }
    });
    showInfoButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        ShowInfo();
      }
    });
  }

  private void SaveDataByPreference() {
    //获取SharedPreference对象
    SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
    //创建一个编辑器对象
    SharedPreferences.Editor editor=sharedPreferences.edit();

    EditText nameEdit = (EditText) findViewById(R.id.name_text);
    EditText ageEdit = (EditText) findViewById(R.id.age_text);

    //存储数据
    String nameStr= String.valueOf(nameEdit.getText());
    String ageStr = String.valueOf(ageEdit.getText());

    editor.putString("userName", nameStr);
    editor.putString("userAge", ageStr);

    //提交保存的数据
    editor.apply();


    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT);
  }
  private void ShowInfo() {
    if(infoView==null)
      return;
    //获取SharedPreference对象
    SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
    //通过键名获取数据，默认值为"N/A"
    String nameStr = sharedPreferences.getString("userName", "N/A");
    String ageStr = sharedPreferences.getString("userAge", "N/A");

    String infoText = getString(R.string.data_info, nameStr, ageStr);
    infoView.setText(infoText);
    infoView.setVisibility(View.VISIBLE);

  }

  @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        GoBack();
    }
    return true;
  }

  private void GoBack() {
    finish();
  }
}
